package com.kll.tv.base.views

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.BasePresenter
import com.kll.tv.utils.AppToast
import com.kll.tv.views.LoginActivity


open abstract class BaseActivity<T: BasePresenter> : AppCompatActivity() {

    lateinit var mPresenter: T

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 创建view层引用并绑定
        mPresenter = createPresenter()

        var view = initViewBinding()
        initView(view)
        init()
    }

    private fun initView(view: View) {

        setContentView(view)

        if (mPresenter != null) {
            mPresenter.onViewAdded()
        }
    }

    /**
     * 初始化ViewBinding
     */
    abstract fun initViewBinding(): View

    abstract fun createPresenter(): T

    abstract fun init()

    override fun onDestroy() {
        super.onDestroy()
        // 解除view绑定
        if(mPresenter != null) {
            mPresenter.onDismiss();
        }
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v is EditText) {  //判断得到的焦点控件是否包含EditText
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            //得到输入框在屏幕中上下左右的位置
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            // 点击位置如果是EditText的区域，忽略它，不收起键盘。
            return (event.x <= left || event.x >= right
                    || event.y <= top || event.y >= bottom)
        }
        // 如果焦点不是EditText则忽略
        return false
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private fun hideKeyboard(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /**
     * 刷新token
     */
    fun refreshToken() {
        // token过期 刷新token
        OperationManager.getInstancce().refreshToken(object : OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                var data = obj as RefreshTokenResponse
                AccountModel.getInstance(baseContext).updateUserToken(data.token)
            }

            override fun onFail(code: Int, message: String) {
                AppToast.show(message, 2000)
                if (code == 101) {
                    loginAgain()
                }
            }

        })
    }

    /**
     * 重新登录
     */
    fun loginAgain() {
        // 跳转登录页面重新登录
        OperationManager.getInstancce().logout()
        startActivity(Intent(this, LoginActivity::class.java))
    }

    /**
     * 点击空白区域隐藏键盘
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.getAction() === MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候
            val v = currentFocus //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, ev)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(v?.getWindowToken());   //收起键盘
            }
        }
        return super.dispatchTouchEvent(ev)
    }

}